package chu.dejian.alarm;

import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CursorAdapter;
import android.widget.TextView;

import com.sam.blemodule.R;
import com.sam.dialog.CustomAlertDialogBuilder;
import com.sam.ui.base.fragment.BaseFragment;
import chu.dejian.ui.fragmet.MeasureAlarmSetFragment;
import chu.dejian.ui.fragmet.MeasureDeviceFragment;
import com.sam.utils.display.DensityUtils;
import com.sam.utils.T;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenu;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenuCreator;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenuItem;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenuListView;
import com.sam.widget.switcher.SwitchButton;
import com.sam.widget.headerBar.BaseHeaderView;
import com.sam.widget.headerBar.LeftImgTitleRightImgBar;

public class MeasureAlarmListFragment extends BaseFragment implements OnItemClickListener{
    private static MeasureAlarmListFragment instance;
    public synchronized static MeasureAlarmListFragment getInstance(){
        if(instance == null){
            instance = new MeasureAlarmListFragment();
        }
        return instance;
    }
    static final String PREFERENCES = "AlarmClock";

    private SwipeMenuListView alarmsListView;
    private Cursor mCursor;
    private LeftImgTitleRightImgBar header;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_measure_alarm_list);
    }

    @Override
    protected void findView() {
        header = (LeftImgTitleRightImgBar) findViewById(R.id.header);
        alarmsListView = (SwipeMenuListView) findViewById(R.id.measure_alarm_list);
    }

    @Override
    protected void initView() {
        header.setOnHeaderClickListener(onHeaderClickListener);
        //取getSharedPreferences中key==“AlarmClock”的值
        mCursor = Alarms.getAlarmsCursor(getActivity().getContentResolver());
        AlarmTimeAdapter adapter = new AlarmTimeAdapter(getActivity(),mCursor);
        alarmsListView.setAdapter(adapter);
        alarmsListView.setVerticalScrollBarEnabled(true);
        alarmsListView.setOnItemClickListener(this);
        alarmsListView.setOnCreateContextMenuListener(this);
    }


    SwipeMenuCreator creator = new SwipeMenuCreator() {

        @Override
        public void create(SwipeMenu menu) {
            SwipeMenuItem deleteBtn = new SwipeMenuItem(getActivity());
            Drawable deleteBg = new ColorDrawable(getResources().getColor(R.color.orange_menu_bg_color));
            deleteBtn.setBackground(deleteBg);
            deleteBtn.setWidth(DensityUtils.dp2px(getActivity(), 60));
            deleteBtn.setTitle(R.string.delete);
            deleteBtn.setTitleSize(16);
            deleteBtn.setTitleColor(Color.WHITE);
            menu.addMenuItem(deleteBtn);
        }
    };

    private SwipeMenuListView.OnMenuItemClickListener onMenuItemClickListener = new SwipeMenuListView.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
            if(index == 0){ // 删除
                try{
                    Alarm alarm = new Alarm((Cursor) alarmsListView.getAdapter().getItem(position));
                    final int id = alarm.id;
                    new CustomAlertDialogBuilder.Builder(getActivity())
                            .setTitle(getString(R.string.delete_alarm))
                            .setMessage(getString(R.string.delete_alarm_confirm))
                            .setPositiveButton(android.R.string.ok,
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface d,
                                                            int w) {
                                            Alarms.deleteAlarm(getActivity(), id);
                                        }
                                    })
                            .setNegativeButton(android.R.string.cancel, null)
                            .create().show();
                }catch (Exception e){
                    T.showLong(getActivity(),getActivity().getString(R.string.alarm_delete_failed));
                }

            }
            return false;
        }
    };

    private BaseHeaderView.OnHeaderClickListener onHeaderClickListener = new BaseHeaderView.OnHeaderClickListener() {
        @Override
        public void onHeaderLeftClicked() {
            replaceSelfWithFragment(MeasureDeviceFragment.getInstance());
        }

        @Override
        public void onHeaderRightClicked() {
            MeasureAlarmSetFragment.getInstance().getArgumentBundle().putInt(Alarms.ALARM_ID, -1);
            replaceSelfWithFragment(MeasureAlarmSetFragment.getInstance());
        }
    };

    /**
     * listview的适配器继承CursorAdapter
     * @author wangxianming
     * 也可以使用BaseAdapter
     */
    private class AlarmTimeAdapter extends CursorAdapter {
        public AlarmTimeAdapter(Context context, Cursor cursor) {
            super(context, cursor);
        }

        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            return LayoutInflater.from(context).inflate(R.layout.row_alarm, parent, false);
        }

        //把view绑定cursor的每一项
        public void bindView(View view, final Context context, Cursor cursor) {
            final Alarm alarm = new Alarm(cursor);
            final SwitchButton enableAlarmSwitcher = (SwitchButton) view.findViewById(R.id.enable_alarm_switcher);
            TextView alarmRepeatStr = (TextView) view.findViewById(R.id.alarm_repeat_str);
            TextView alarmTime = (TextView) view.findViewById(R.id.alarm_time);

            enableAlarmSwitcher.setChecked(alarm.enabled);
            enableAlarmSwitcher.setOnCheckChangeListener(new SwitchButton.OnCheckChangeListener() {
                @Override
                public void OnCheck(SwitchButton switchButton, boolean isChecked) {
                    Alarms.enableAlarm(context, alarm.id, isChecked);
                    if (isChecked) {
                        SetAlarm.popAlarmSetToast(context, alarm.hour, alarm.minutes,alarm.daysOfWeek);
                    }
                }
            });

            alarmTime.setText(String.format("%02d",alarm.hour) + ":" + String.format("%02d",alarm.minutes));

            // Set the repeat text or leave it blank if it does not repeat.
            final String daysOfWeekStr = alarm.daysOfWeek.toString(context, false);
            if (daysOfWeekStr != null && daysOfWeekStr.length() != 0) {
                alarmRepeatStr.setText(daysOfWeekStr);
            } else {
                alarmRepeatStr.setText(getResources().getString(R.string.no_repeat));
            }
        }
    }

	public void onItemClick(AdapterView<?> adapterView, View v, int pos, long id) {
        MeasureAlarmSetFragment.getInstance().getArgumentBundle().putInt(Alarms.ALARM_ID, (int) id);
        replaceSelfWithFragment(MeasureAlarmSetFragment.getInstance());
	}
	
   @Override
   public void onDestroy() {
        super.onDestroy();
        ToastMaster.cancelToast();
       if(mCursor != null) mCursor.close();
    }
}